﻿using System.Security.Cryptography;
using System.Text;

/********************************************
* 公司名称：snail information
* 创 建 人：iFeihang
* 创建日期：2025/9/29 14:48:25
* 说    明：
* 版    本：V0.0.0.1
********************************************/
namespace SnailInfo.ConvertExtension
{
    /// <summary>
    /// get hash string for object
    /// </summary>
    public static class HashExtensions
    {
        /// <summary>
        /// get hash string of byte by MD5
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string GetMD5Hash(this byte[] data)
        {
            using (var md5 = MD5.Create()) {
                var hashData = md5.ComputeHash(data);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < hashData.Length; i++) {
                    stringBuilder.Append(hashData[i].ToString("x2"));
                }
                
                return stringBuilder.ToString();
            }
        }
        /// <summary>
        /// get hash string of stream by MD5
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string GetMD5Hash(this Stream stream)
        {
            using (var md5 = MD5.Create()) {
                var hashData = md5.ComputeHash(stream);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < hashData.Length; i++) {
                    stringBuilder.Append(hashData[i].ToString("x2"));
                }

                string encryptString = stringBuilder.ToString();
                return encryptString;
            }
        }
        /// <summary>
        /// get hash string of FileInfo by MD5
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        public static string GetMD5Hash(this FileInfo fileInfo)
        {
            if (fileInfo is null) { return string.Empty; }
            using (Stream stream = fileInfo.OpenRead()) {
                using var md5 = MD5.Create();
                var hashData = md5.ComputeHash(stream);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < hashData.Length; i++) {
                    stringBuilder.Append(hashData[i].ToString("x2"));
                }

                string encryptString = stringBuilder.ToString();
                return encryptString;
            }
        }
    }
}
